package com.fp.m7.server.auth;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.fp.m7.api.manager.AccountManager;
import com.fp.m7.api.model.Account;
import com.fp.m7.shared.exception.GwtAuthenticationException;

/**
 * An authentication checker - has methods for checking if the user is logged in (using spring security context).
 */
@Component
public class AuthenticationChecker {
    private static final Logger logger = LoggerFactory.getLogger(AuthenticationChecker.class);

    @Autowired
    protected AccountManager accountManager;

    /**
     * Checks if the user who invoked the service method is logged in. If so - returns his username, otherwise throws a
     * security exception.
     * 
     * @return username of the logged user
     */
    public String getLoggedUsername() throws GwtAuthenticationException {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth instanceof CustomAuthentication) {
            Object principal = auth.getPrincipal();
            if (principal instanceof String) {
                return (String) principal;
            }
        }

        String log = "Unauthorized access attempt.";
        logger.info(log);
        throw new GwtAuthenticationException(log);
    }

    /**
     * @return the account object associated to the username in an active session
     */
    public Account getLoggedAccount() throws GwtAuthenticationException {
        String username = getLoggedUsername();
        return accountManager.findByUsername(username);
    }

    public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}
}
